<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="聚焦Java性能优化 打造亿级流量秒杀系统,">










<meta name="description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill 本文为第四章分布式扩展的内容">
<meta name="keywords" content="聚焦Java性能优化 打造亿级流量秒杀系统">
<meta property="og:type" content="article">
<meta property="og:title" content="【十】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2020/02/02/second-kill-system-step-by-step-10/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill 本文为第四章分布式扩展的内容">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200203215600917.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204091420981.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204140617836.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204142211517.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204142120912.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200203223809123.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200203230450298.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200203230110476.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204153711938.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200204154225312.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205065821133.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205065534778.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205070047109.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200203223809123.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205071654079.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205145625160.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205223516546.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200205223516546.jpg">
<meta property="og:updated_time" content="2020-02-08T06:26:08.194Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【十】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展">
<meta name="twitter:description" content="本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记实战视频地址： https://coding.imooc.com/class/chapter/338.html前期免费视频地址： http://www.imooc.com/learn/1079代码地址：https://gitee.com/aiolos123/secondkill 本文为第四章分布式扩展的内容">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20200203215600917.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2020/02/02/second-kill-system-step-by-step-10/">





  <title>【十】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2020/02/02/second-kill-system-step-by-step-10/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【十】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-02-02T22:59:13+08:00">
                2020-02-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/SpringBoot/" itemprop="url" rel="index">
                    <span itemprop="name">SpringBoot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网 《聚焦Java性能优化 打造亿级流量秒杀系统》视频教程的学习笔记<br>实战视频地址： <a href="https://coding.imooc.com/class/chapter/338.html" target="_blank" rel="noopener">https://coding.imooc.com/class/chapter/338.html</a><br>前期免费视频地址： <a href="http://www.imooc.com/learn/1079" target="_blank" rel="noopener">http://www.imooc.com/learn/1079</a><br>代码地址：<a href="https://gitee.com/aiolos123/secondkill" target="_blank" rel="noopener">https://gitee.com/aiolos123/secondkill</a></p>
<p>本文为第四章分布式扩展的内容</p>
<a id="more"></a>

<p>在上一章通过jmeter压测，优化了Tomcat的相关配置，发现了容器的瓶颈和数据库的瓶颈。从本章开始将解决这些瓶颈问题。第一个优化方案就是本章的分布式扩展。</p>
<h2 id="本章内容"><a href="#本章内容" class="headerlink" title="本章内容"></a>本章内容</h2><ol>
<li>nginx反向代理负载均衡</li>
<li>分布式会话管理</li>
<li>使用Redis实现分布式会话存储</li>
</ol>
<h2 id="单机容量问题"><a href="#单机容量问题" class="headerlink" title="单机容量问题"></a>单机容量问题</h2><ol>
<li><p>启动jmeter，设置线程数在500，循环20次，发现单台机器的TPS上限在200左右</p>
</li>
<li><p>单机容量问题(即top H的指标)</p>
<blockquote>
<p>表象： 单机CPU使用率增高，memory占用增加，网络带宽使用增加<br>cpu us: 用户空间的cpu使用情况百分比(用户层代码)<br>cpu sy: 内核空间的cpu使用情况百分比(系统调用)<br>load average: 1、5、15分钟load平均值，跟着cpu的核数的系数走，在1核情况下：0代表通畅，1代表打满，1+代表等待阻塞<br>memory: free表示空闲内存， used表示使用内存</p>
</blockquote>
</li>
<li><p>单机容量问题的优化方案————水平扩展</p>
<blockquote>
<p>单点mysql数据库服务器————mysql数据库开放远端连接<br>服务端水平对称部署<br>验证访问</p>
</blockquote>
</li>
<li><p>改进前后的部署方案如下图(<strong>从1台服务器扩展到四台服务器</strong>)：<br><img src="/blog/images/20200203215600917.jpg" alt="改进前后的部署方案"></p>
</li>
</ol>
<h2 id="数据库开放远程连接端口"><a href="#数据库开放远程连接端口" class="headerlink" title="数据库开放远程连接端口"></a>数据库开放远程连接端口</h2><ol>
<li>按照上图所述，部署4台服务器(本人执行的是虚拟机克隆操作)，分别作为数据库服务器(1台)、应用程序服务器(2台)、nginx服务器(1台)<blockquote>
<p>192.168.126.131 : 应用程序服务器<br>192.168.126.132 : 数据库服务器<br>192.168.126.133 : 应用程序服务器<br>192.168.126.134 : nginx服务器</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20200204091420981.jpg" alt="部署4台服务器"></p>
<blockquote>
<p>MySQL数据库开放远程连接端口请见视频《4-2》</p>
</blockquote>
<ol>
<li><p>MySQL开放数据库远程连接权限的命令是如下两条：</p>
<blockquote>
<p>(授权所有权限给所有域名，只要用户名和密码正确)命令： grant all privileges on <em>.</em> to root@’%’ identified by ‘root’;<br>(授权生效命令) flush privileges;</p>
</blockquote>
</li>
<li><p>本人使用的是pgsql数据库</p>
<blockquote>
<p><strong>CentoS上安装pgsql及开放远程端口请见：/blog/2020/01/09/how-to-install-pgsql-on-centos6.8/</strong></p>
</blockquote>
</li>
<li><p>通过”telnet Ip 端口号”测试数据库远程端口是否开放，如果出现下面的界面，则说出远程端口已开放</p>
<blockquote>
<p>如果未安装telnet，则可通过 yum install telnet 命令安装</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20200204140617836.jpg" alt="测试数据库远程端口是否开放"></p>
<h2 id="水平扩展应用程序服务器"><a href="#水平扩展应用程序服务器" class="headerlink" title="水平扩展应用程序服务器"></a>水平扩展应用程序服务器</h2><blockquote>
<p>192.168.126.131 : 应用程序服务器<br>192.168.126.132 : 数据库服务器<br>192.168.126.133 : 应用程序服务器<br>192.168.126.134 : nginx服务器</p>
</blockquote>
<ol>
<li><p>部署两台应用程序服务器(修改application.yml中的数据库连接)<br><img src="/blog/images/20200204142211517.jpg" alt="测试数据库远程端口是否开放"></p>
</li>
<li><p>启动应用，验证水平扩展成功<br><img src="/blog/images/20200204142120912.jpg" alt="测试数据库远程端口是否开放"></p>
</li>
</ol>
<h2 id="修改前端资源用于部署nginx"><a href="#修改前端资源用于部署nginx" class="headerlink" title="修改前端资源用于部署nginx"></a>修改前端资源用于部署nginx</h2><ol>
<li>由于nginx只能作为静态web服务器，对于动态请求需要通过反向代理，所以继续优化我们的部署方案，如下图：<br><img src="/blog/images/20200203223809123.jpg" alt="改进后的部署方案"></li>
</ol>
<p><strong>并规定如果是访问/resource路径，则走静态资源的访问路径；否则走反向代理的访问路径；</strong></p>
<ol start="2">
<li><p>分离前端资源<br><img src="/blog/images/20200203230450298.jpg" alt="分离前端资源"></p>
</li>
<li><p>使用全局变量替换前端资源ajax请求中的url地址前缀，方便统一修改<br><img src="/blog/images/20200203230110476.jpg" alt="使用全局变量替换前端ajax请求中的url地址前缀"></p>
</li>
</ol>
<h2 id="安装部署Nginx-OpenResty"><a href="#安装部署Nginx-OpenResty" class="headerlink" title="安装部署Nginx OpenResty"></a>安装部署Nginx OpenResty</h2><ol>
<li><p>nginx的主要业务功能有如下三块：</p>
<blockquote>
<p>使用nginx作为静态web服务器；<br>使用nginx作为动静分离服务器；<br>使用nginx作为反向代理服务器；</p>
</blockquote>
</li>
<li><p>永久关闭防火墙</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">service iptables status</span><br><span class="line">service iptables stop</span><br><span class="line">chkconfig iptables off</span><br></pre></td></tr></table></figure>
</li>
<li><p>安装Nginx OpenResty</p>
<blockquote>
<p>Nginx官网下载的Nginx都是基于源代码的，Nginx是按需加载模块，需要手动加载、编译、配置模块，<br>鉴于开发者在最初使用Nginx时，无法熟悉Nginx各模块。 如果做Nginx开放调优工作，强烈推荐使用OpenResty框架</p>
</blockquote>
</li>
</ol>
<p>OpenResty官网：<a href="http://openresty.org/cn/" target="_blank" rel="noopener">http://openresty.org/cn/</a></p>
<blockquote>
<p>OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台，其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。</p>
</blockquote>
<p><strong>OpenResty并非是Nginx开发框架的唯一选择，它只是在Nginx基础上开发、包装，支持了Lua等的一个应用</strong></p>
<ol start="4">
<li>OpenResty安装过程的命令如下：<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"># 安装前的准备</span><br><span class="line"># 您必须将这些库 perl <span class="number">5.6</span><span class="number">.1</span>+, libpcre, libssl安装在您的电脑之中</span><br><span class="line">yum install pcre-devel openssl-devel gcc curl</span><br><span class="line"># 解压</span><br><span class="line">tar -xvzf openresty<span class="number">-1.13</span><span class="number">.6</span><span class="number">.2</span>.tar.gz</span><br><span class="line">cd openresty<span class="number">-1.13</span><span class="number">.6</span><span class="number">.2</span></span><br><span class="line">./configure</span><br><span class="line">gmake</span><br><span class="line">gmake insall</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>OpenResty安装过程的截图如下：<br><img src="/blog/images/20200204153711938.jpg" alt="OpenResty安装过程的截图"></p>
<ol start="4">
<li>按照上述安装完成后，openResty安装到 /usr/local/openresty/ 目录下，其目录结构如下：<br><img src="/blog/images/20200204154225312.jpg" alt="OpenResty目录结构"></li>
</ol>
<h2 id="配置Ngnix为Web服务器"><a href="#配置Ngnix为Web服务器" class="headerlink" title="配置Ngnix为Web服务器"></a>配置Ngnix为Web服务器</h2><h3 id="部署前端资源"><a href="#部署前端资源" class="headerlink" title="部署前端资源"></a>部署前端资源</h3><ol>
<li><p>启动Nginx： 进入nginx目录，执行命令：sbin/nginx -c conf/nginx.conf<br><img src="/blog/images/20200205065821133.jpg" alt="启动Nginx"></p>
</li>
<li><p>上传本地的前端资源到nginx的html目录下(/usr/local/openresty/nginx/html)<br><img src="/blog/images/20200205065534778.jpg" alt="上传本地的前端资源"></p>
</li>
</ol>
<p>测试文件上传成功，如下图：<br><img src="/blog/images/20200205070047109.jpg" alt="上传本地的前端资源"></p>
<h3 id="在Nginx中配置前端路由"><a href="#在Nginx中配置前端路由" class="headerlink" title="在Nginx中配置前端路由"></a>在Nginx中配置前端路由</h3><p>接下来，按照之前提出的优化方案(如下图)，修改Nignx配置<br><img src="/blog/images/20200203223809123.jpg" alt="改进后的部署方案"></p>
<p>具体修改Nignx配置的内容为：</p>
<blockquote>
<p>a. location节点path: 指定url映射key<br>b. location节点内容： root指定location path后对应的根路径， index指定默认的访问页</p>
</blockquote>
<ol>
<li>修改nginx.conf配置文件，指定访问/resources/路径时，就会访问前端资源<br><img src="/blog/images/20200205071654079.jpg" alt="修改nginx.conf配置文件"></li>
</ol>
<p><strong>alias的作用：当URL访问/resources/的路径时，将其映射到/usr/local/openresty/nginx/html/resources/目录下</strong></p>
<ol start="2">
<li>无缝重启nginx： 修改配置后，直接执行 sbin/nginx -s reload<br><img src="/blog/images/20200205145625160.jpg" alt="无缝重启nginx"></li>
</ol>
<blockquote>
<p>无缝重启nginx： 重启nginx时，主进程不变，工作进程改变: 处理socket连接的进程正是这个工作进程</p>
</blockquote>
<p>至此，我们完成了Nginx作为Web服务器的功能。</p>
<h2 id="配置nginx为动静分离服务器和反向代理服务器"><a href="#配置nginx为动静分离服务器和反向代理服务器" class="headerlink" title="配置nginx为动静分离服务器和反向代理服务器"></a>配置nginx为动静分离服务器和反向代理服务器</h2><ol start="0">
<li>通过nginx反向代理实现水平扩展<blockquote>
<p>通过nginx反向代理实现：同一个域名代理到多台应用服务器上</p>
</blockquote>
</li>
</ol>
<p>配置动静分离服务器时，具体修改Nignx配置的内容为：</p>
<blockquote>
<p>a. 配置location节点 /resources/路径： 为静态资源路径<br>b. 配置location节点其他路径： 为动态资源路径, 即配置nginx为反向代理服务器</p>
</blockquote>
<p>配置动态资源的方式，具体修改Nignx配置的内容为：</p>
<ol>
<li><p>设备upstream server</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># "upstream server名称"是nginx真正的反向代理的节点</span></span><br><span class="line"><span class="comment"># 本例为指定反向代理的服务器为131和133，并且他们的访问权重都是1，即负载均衡是轮询访问</span></span><br><span class="line">upstream backend_server&#123;</span><br><span class="line">      <span class="built_in"> server </span>192.168.126.131 <span class="attribute">weight</span>=1;</span><br><span class="line">      <span class="built_in"> server </span>192.168.126.133 <span class="attribute">weight</span>=1;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置动态请求location为proxy_pass路径</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> / &#123;</span><br><span class="line">           <span class="attribute">proxy_pass</span> http://backend_server;</span><br><span class="line">           <span class="attribute">proxy_set_header</span> Host <span class="variable">$http_host</span>:<span class="variable">$proxy_port</span>;</span><br><span class="line">           <span class="attribute">proxy_set_header</span> X-Real-IP <span class="variable">$remote_addr</span>;</span><br><span class="line">           <span class="attribute">proxy_set_header</span> X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>上述两步的配置截图如下：<br><img src="/blog/images/20200205223516546.jpg" alt="无缝重启nginx"></p>
<ol start="3">
<li><p>重启nginx，访问静态资源和动态资源，验证反向代理配置成功，如下图：<br><img src="/blog/images/20200205223516546.jpg" alt="验证反向代理配置成功"></p>
</li>
<li><p>开启tomcat access log验证反向代理访问真正Tomcat成功</p>
<blockquote>
<p>在生成环境中推荐打开tomcat access log，用于记录日志和性能。 </p>
</blockquote>
</li>
</ol>
<p>打开的命令如下：</p>
<figure class="highlight llvm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 创建用于保存tomcat access log的目录</span><br><span class="line">mkdir tomcat</span><br><span class="line">chmod -R <span class="number">777</span> tomcat/</span><br><span class="line"># 然后在application.yml中开启tomcat access log</span><br><span class="line">server：</span><br><span class="line">    tomcat：</span><br><span class="line">       accesslog：</span><br><span class="line">          enabled： <span class="keyword">true</span></span><br><span class="line">          directory： /home/tomcat</span><br><span class="line">          #请求IP <span class="symbol">%l</span> 请求用户 处理时间 请求的url和方法 http返回状态码 响应数据大小 请求处理时长</span><br><span class="line">          pattern： '<span class="symbol">%h</span> <span class="symbol">%l</span> <span class="symbol">%u</span> <span class="symbol">%t</span> <span class="string">"%r"</span> <span class="symbol">%s</span> <span class="symbol">%b</span> <span class="symbol">%D</span>'</span><br></pre></td></tr></table></figure>

<p>如下图： <a href="http://192.168.126.131/item/get?id=1" target="_blank" rel="noopener">http://192.168.126.131/item/get?id=1</a></p>
<p><strong>注意: 修改前端静态资源中的g_host全局变量为nginx服务器IP地址或域名</strong></p>
<p>至此，Nginx反向代理配置完成。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/聚焦Java性能优化-打造亿级流量秒杀系统/" rel="tag"># 聚焦Java性能优化 打造亿级流量秒杀系统</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2020/01/31/second-kill-system-step-by-step-9/" rel="next" title="【九】聚焦Java性能优化 打造亿级流量秒杀系统——性能压测">
                <i class="fa fa-chevron-left"></i> 【九】聚焦Java性能优化 打造亿级流量秒杀系统——性能压测
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2020/02/08/second-kill-system-step-by-step-11/" rel="prev" title="【十一】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展后的性能压测">
                【十一】聚焦Java性能优化 打造亿级流量秒杀系统——分布式扩展后的性能压测 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#本章内容"><span class="nav-number">1.</span> <span class="nav-text">本章内容</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单机容量问题"><span class="nav-number">2.</span> <span class="nav-text">单机容量问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库开放远程连接端口"><span class="nav-number">3.</span> <span class="nav-text">数据库开放远程连接端口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#水平扩展应用程序服务器"><span class="nav-number">4.</span> <span class="nav-text">水平扩展应用程序服务器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改前端资源用于部署nginx"><span class="nav-number">5.</span> <span class="nav-text">修改前端资源用于部署nginx</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装部署Nginx-OpenResty"><span class="nav-number">6.</span> <span class="nav-text">安装部署Nginx OpenResty</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置Ngnix为Web服务器"><span class="nav-number">7.</span> <span class="nav-text">配置Ngnix为Web服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#部署前端资源"><span class="nav-number">7.1.</span> <span class="nav-text">部署前端资源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#在Nginx中配置前端路由"><span class="nav-number">7.2.</span> <span class="nav-text">在Nginx中配置前端路由</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置nginx为动静分离服务器和反向代理服务器"><span class="nav-number">8.</span> <span class="nav-text">配置nginx为动静分离服务器和反向代理服务器</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
